<template>
  <div class="forgot-password-container">
    <div class="forgot-password-box">
      <div class="login-header">
        <h2>忘记密码</h2>
        <p>通过手机号或邮箱重置您的密码</p>
      </div>
      
      <van-cell-group class="cell-group">
        <!-- 优化后的验证方式选择 -->
        <div class="verify-type-container">
          <div 
            class="verify-type-option"
            :class="{ 'active': verifyType === 'phone' }"
            @click="switchVerifyType('phone')"
          >
            <van-icon name="phone-o" size="18" />
            <span>手机号</span>
          </div>
          <div 
            class="verify-type-option"
            :class="{ 'active': verifyType === 'email' }"
            @click="switchVerifyType('email')"
          >
            <van-icon name="envelop-o" size="18" />
            <span>邮箱</span>
          </div>
        </div>
        
        <!-- 账号输入 - 动态属性 -->
        <van-field
          v-model="form.account"
          :label="verifyType === 'phone' ? '手机号' : '邮箱'"
          :placeholder="verifyType === 'phone' ? '请输入11位手机号' : '请输入注册邮箱'"
          :type="verifyType === 'phone' ? 'tel' : 'email'"
          :rules="accountRules"
          class="login-field"
          @blur="validateAccount"
          @input="formatAccountInput"
          clearable
        />
        
        <!-- 验证码输入 -->
        <van-field
          v-model="form.code"
          label="验证码"
          placeholder="请输入6位验证码"
          :rules="codeRules"
          class="login-field"
          @blur="validateCode"
          clearable
        >
          <template #button>
            <van-button
              size="mini"
              type="info"
              @click="sendVerifyCode"
              :disabled="isSending || !form.account"
            >
              {{ isSending ? count + 's后重发' : '发送验证码' }}
            </van-button>
          </template>
        </van-field>
        
        <!-- 新密码输入 -->
        <van-field
          v-model="form.newPassword"
          label="新密码"
          :type="showPassword ? 'text' : 'password'"
          placeholder="请设置6-20位新密码"
          :rules="passwordRules"
          class="login-field"
          @input="checkPasswordStrength"
          @blur="validatePassword"
          clearable
        >
          <template #button>
            <van-icon
              @click="showPassword = !showPassword"
              :name="showPassword ? 'eye-o' : 'closed-eye'"
            />
          </template>
        </van-field>
        
        <!-- 密码强度提示 -->
        <div v-if="form.newPassword" class="password-strength">
          <div class="strength-bar">
            <div
              class="strength-segment"
              :class="{ 'weak': passwordStrength >= 1, 'medium': passwordStrength >= 2, 'strong': passwordStrength >= 3, 'very-strong': passwordStrength >= 4 }"
            ></div>
          </div>
          <div class="strength-text">{{ passwordStrengthText }}</div>
        </div>
        
        <!-- 确认密码输入 -->
        <van-field
          v-model="form.confirmPassword"
          label="确认密码"
          :type="showConfirmPassword ? 'text' : 'password'"
          placeholder="请再次输入新密码"
          :rules="confirmPasswordRules"
          class="login-field"
          @blur="validateConfirmPassword"
          clearable
        >
          <template #button>
            <van-icon
              @click="showConfirmPassword = !showConfirmPassword"
              :name="showConfirmPassword ? 'eye-o' : 'closed-eye'"
            />
          </template>
        </van-field>
        
        <!-- 提交按钮 -->
        <van-button 
          @click="resetPassword" 
          type="primary" 
          size="large" 
          block 
          class="login-button"
          :loading="isLoading"
          :disabled="!formValid"
        >
          {{ isLoading ? '重置中...' : '重置密码' }}
        </van-button>
      </van-cell-group>
      
      <!-- 返回登录 -->
      <div class="goto-login">
        <van-button plain  @click="goToLogin" class="back-to-login">
          记得密码？返回登录
        </van-button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';

export default {
  setup() {
    const router = useRouter();
    
    // 表单数据
    const verifyType = ref('phone');
    const form = ref({
      account: '',
      code: '',
      newPassword: '',
      confirmPassword: ''
    });
    
    // UI状态
    const isSending = ref(false);
    const count = ref(60);
    const isLoading = ref(false);
    const showPassword = ref(false);
    const showConfirmPassword = ref(false);
    const passwordStrength = ref(0);
    const passwordStrengthText = ref('密码强度: 弱');
    
    // 切换验证方式
    const switchVerifyType = (type) => {
      verifyType.value = type;
      form.value.account = '';
      form.value.code = '';
    };
    
    // 格式化账号输入
    const formatAccountInput = () => {
      if (verifyType.value === 'phone') {
        // 手机号格式化：123 4567 8901
        form.value.account = form.value.account
          .replace(/\D/g, '')
          .replace(/(\d{3})(\d{0,4})(\d{0,4})/, (_, $1, $2, $3) => {
            let result = $1;
            if ($2) result += ' ' + $2;
            if ($3) result += ' ' + $3;
            return result;
          })
          .trim();
      } else {
        // 邮箱自动转小写
        form.value.account = form.value.account.toLowerCase();
      }
    };
    
    // 验证账号
    const validateAccount = () => {
      if (verifyType.value === 'phone') {
        const phone = form.value.account.replace(/\s/g, '');
        if (!/^1[3-9]\d{9}$/.test(phone)) {
          showToast('请输入正确的11位手机号');
          return false;
        }
      } else {
        if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(form.value.account)) {
          showToast('请输入有效的邮箱地址');
          return false;
        }
      }
      return true;
    };
    
    // 验证验证码
    const validateCode = () => {
      if (!/^\d{6}$/.test(form.value.code)) {
        showToast('请输入6位数字验证码');
        return false;
      }
      return true;
    };
    
    // 验证密码
    const validatePassword = () => {
      if (form.value.newPassword.length < 6) {
        showToast('密码长度不能小于6位');
        return false;
      }
      return true;
    };
    
    // 验证确认密码
    const validateConfirmPassword = () => {
      if (form.value.confirmPassword !== form.value.newPassword) {
        showToast('两次输入的密码不一致');
        return false;
      }
      return true;
    };
    
    // 发送验证码
    const sendVerifyCode = () => {
      if (!validateAccount()) return;
      
      isSending.value = true;
      count.value = 60;
      
      // 根据验证类型显示不同提示
      const target = verifyType.value === 'phone' 
        ? `手机号 ${form.value.account}` 
        : `邮箱 ${form.value.account}`;
      
      showToast(`验证码已发送至 ${target}`);
      
      // 倒计时
      const timer = setInterval(() => {
        if (count.value <= 1) {
          clearInterval(timer);
          count.value = 60;
          isSending.value = false;
        } else {
          count.value--;
        }
      }, 1000);
    };
    
    // 检查密码强度
    const checkPasswordStrength = () => {
      const password = form.value.newPassword;
      if (!password) {
        passwordStrength.value = 0;
        passwordStrengthText.value = '密码强度: 弱';
        return;
      }
      
      let strength = 0;
      
      // 长度评分
      if (password.length >= 6) strength += 1;
      if (password.length >= 8) strength += 1;
      
      // 复杂度评分
      if (/[0-9]/.test(password)) strength += 1;
      if (/[a-z]/.test(password)) strength += 1;
      if (/[A-Z]/.test(password)) strength += 1;
      if (/[^0-9a-zA-Z]/.test(password)) strength += 1;
      
      // 限制强度范围
      passwordStrength.value = Math.min(Math.max(strength, 0), 4);
      
      // 设置强度文本
      const strengthTexts = ['弱', '中', '强', '很强', '极强'];
      passwordStrengthText.value = `密码强度: ${strengthTexts[passwordStrength.value]}`;
    };
    
    // 重置密码
    const resetPassword = async () => {
      if (!formValid.value) {
        showToast('请填写完整的表单信息');
        return;
      }
      
      isLoading.value = true;
      
      try {
        // 模拟API请求
        await new Promise(resolve => setTimeout(resolve, 1500));
        
        showToast('密码重置成功！');
        router.push({ name: 'login' });
      } catch (error) {
        showToast('重置失败，请稍后重试');
        console.error('重置密码错误:', error);
      } finally {
        isLoading.value = false;
      }
    };
    
    // 返回登录页面
    const goToLogin = () => {
      router.push({ name: 'login' });
    };
    
    // 表单验证状态
    const formValid = computed(() => {
      return (
        form.value.account && 
        form.value.code && 
        form.value.newPassword && 
        form.value.confirmPassword &&
        validateAccount() &&
        validateCode() &&
        validatePassword() &&
        validateConfirmPassword()
      );
    });
    
    // 动态验证规则
    const accountRules = [
      { 
        validator: (val) => {
          if (verifyType.value === 'phone') {
            const phone = val.replace(/\s/g, '');
            return /^1[3-9]\d{9}$/.test(phone);
          } else {
            return /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(val);
          }
        },
        message: () => {
          return verifyType.value === 'phone' 
            ? '请输入正确的11位手机号' 
            : '请输入有效的邮箱地址';
        },
        trigger: 'blur'
      }
    ];
    
    const codeRules = [
      { required: true, message: '请输入验证码', trigger: 'blur' },
      { pattern: /^\d{6}$/, message: '请输入6位数字验证码', trigger: 'blur' }
    ];
    
    const passwordRules = [
      { required: true, message: '请设置新密码', trigger: 'blur' },
      { min: 6, message: '密码长度不能小于6位', trigger: 'blur' },
      { max: 20, message: '密码长度不能超过20位', trigger: 'blur' }
    ];
    
    const confirmPasswordRules = [
      { required: true, message: '请确认新密码', trigger: 'blur' },
      { 
        validator: (val) => val === form.value.newPassword,
        message: '两次输入的密码不一致',
        trigger: 'blur'
      }
    ];
    
    return {
      verifyType,
      form,
      isSending,
      count,
      isLoading,
      showPassword,
      showConfirmPassword,
      passwordStrength,
      passwordStrengthText,
      formValid,
      accountRules,
      codeRules,
      passwordRules,
      confirmPasswordRules,
      switchVerifyType,
      formatAccountInput,
      validateAccount,
      validateCode,
      validatePassword,
      validateConfirmPassword,
      sendVerifyCode,
      checkPasswordStrength,
      resetPassword,
      goToLogin
    };
  }
};
</script>

<style lang="less" scoped>
@bg-color: #f7f8fa;
@primary-color: #1989fa;
@secondary-color: #f5f5f5;
@text-color: #333;
@border-color: #ebedf0;
@error-color: #ee0a24;
@success-color: #07c160;

.forgot-password-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: @bg-color;
  padding: 20px;
}

.forgot-password-box {
  width: 100%;
  max-width: 420px;
  padding: 24px;
  background-color: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.login-header {
  text-align: center;
  margin-bottom: 28px;
  
  h2 {
    font-size: 24px;
    font-weight: 600;
    color: @text-color;
    margin-bottom: 8px;
  }
  
  p {
    font-size: 14px;
    color: #999;
  }
}

.cell-group {
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 20px;
}

/* 验证方式切换样式 */
.verify-type-container {
  display: flex;
  background-color: @secondary-color;
  border-radius: 8px;
  padding: 4px;
  margin-bottom: 20px;
}

.verify-type-option {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 0;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  
  .van-icon {
    margin-bottom: 6px;
    color: #666;
    transition: all 0.3s ease;
  }
  
  span {
    font-size: 14px;
    color: #666;
    transition: all 0.3s ease;
  }
  
  &.active {
    background-color: @primary-color;
    
    .van-icon, span {
      color: white;
    }
  }
}

.login-field {
  margin-bottom: 16px;
  
  &:last-child {
    margin-bottom: 0;
  }
}

/* 密码强度指示器 */
.password-strength {
  margin: -8px 0 16px;
  padding: 0 16px;
  
  .strength-bar {
    height: 4px;
    background-color: #ebedf0;
    border-radius: 2px;
    overflow: hidden;
    margin-bottom: 4px;
    
    .strength-segment {
      height: 100%;
      width: 100%;
      transform-origin: left;
      transform: scaleX(0);
      transition: all 0.3s ease;
      
      &.weak {
        transform: scaleX(0.25);
        background-color: @error-color;
      }
      
      &.medium {
        transform: scaleX(0.5);
        background-color: #ff976a;
      }
      
      &.strong {
        transform: scaleX(0.75);
        background-color: #ffd700;
      }
      
      &.very-strong {
        transform: scaleX(1);
        background-color: @success-color;
      }
    }
  }
  
  .strength-text {
    font-size: 12px;
    color: #969799;
    text-align: right;
  }
}

.login-button {
  margin-top: 24px;
  border-radius: 8px;
  font-weight: 500;
  height: 44px;
}

.goto-login {
  text-align: center;
  margin-top: 16px;
  
  .back-to-login {
    height: auto;
    padding: 0;
    font-size: 14px;
    color: @primary-color;
    
    &::after {
      border: none;
    }
  }
}

/* 手机号输入优化 */
.van-field__control[type="tel"] {
  letter-spacing: 1px;
}

/* 响应式调整 */
@media (max-width: 375px) {
  .forgot-password-box {
    padding: 16px;
  }
  
  .login-header h2 {
    font-size: 22px;
  }
}
</style>